<template>
  <div class="cool-filter-container">
    <!-- 悬浮筛选按钮 -->
    <el-button 
      type="primary" 
      @click="drawerVisible = true"
      class="floating-filter-button"
      :class="{'hidden-xs-only': drawerVisible}"
    >
      <span class="vertical-text">
        <span class="hidden-xs-only">选<br>筛</span>
        <el-icon class="hidden-sm-and-up"><i-ep-filter /></el-icon>
      </span>
    </el-button>

    <!-- 左侧抽屉筛选器 -->
    <el-drawer 
      v-model="drawerVisible" 
      :title="title" 
      direction="ltr"
      :size="size"
    >
      <div class="filter-content">
        <el-checkbox-group v-model="internalSelectedTags">
          <el-checkbox 
            v-for="tag in tags" 
            :key="tag.id" 
            :label="tag.id"
            class="filter-tag"
          >
            <el-icon><component :is="tag.icon" /></el-icon>
            {{ tag.label }}
          </el-checkbox>
        </el-checkbox-group>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue';

const props = defineProps({
  tags: {
    type: Array,
    default: () => [
      { id: 'tech', label: '技术', icon: 'CoffeeCup' },
      { id: 'design', label: '设计', icon: 'Brush' },
      { id: 'business', label: '商业', icon: 'TrendCharts' },
      { id: 'health', label: '健康', icon: 'FirstAidKit' },
      { id: 'education', label: '教育', icon: 'Notebook' },
      { id: 'entertainment', label: '娱乐', icon: 'Film' },
      { id: 'sports', label: '体育', icon: 'Basketball' },
      { id: 'travel', label: '旅行', icon: 'MapLocation' }
    ]
  },
  modelValue: {
    type: Array,
    default: () => []
  },
  title: {
    type: String,
    default: '标签筛选'
  },
  size: {
    type: String,
    default: '180px'
  }
});

const emit = defineEmits(['update:modelValue', 'change']);

const drawerVisible = ref(false);
// 使用内部变量来避免递归更新
const internalSelectedTags = ref([...props.modelValue]);

// 监听外部传入的modelValue变化
watch(() => props.modelValue, (newValue) => {
  // 只有当值确实不同时才更新
  if (JSON.stringify(newValue) !== JSON.stringify(internalSelectedTags.value)) {
    internalSelectedTags.value = [...newValue];
  }
});

// 监听内部选择变化
watch(internalSelectedTags, (newValue) => {
  // 使用nextTick确保在下一个更新周期触发，避免递归
  nextTick(() => {
    emit('update:modelValue', [...newValue]);
    emit('change', [...newValue]);
  });
}, { deep: true });
</script>

<style scoped>
.cool-filter-container {
  position: relative;
}

.floating-filter-button {
  position: fixed;
  left: 0;
  top: 25%;
  transform: translateY(-50%);
  z-index: 2000;
  padding: 15px 5px;
  border-radius: 0 8px 8px 0;
  writing-mode: vertical-rl;
  height: auto;
}

.vertical-text {
  writing-mode: vertical-rl;
  text-orientation: upright;
  letter-spacing: 5px;
}

.filter-content {
  padding: 20px;
}

.filter-tag {
  display: block;
  margin: 10px 0;
}
</style>